<?php
/**
 * 资源公共控制器
 * Created by PhpStorm.
 * User: yui
 * Date: 2017/4/21
 * Time: 2:36
 */

namespace common\controllers;

use Yii;
use yii\web\Response;

class AssetsCommonCtrl extends CommonCtrl
{
    public $enableCsrfValidation = false;

    /**
     * 用户token
     * @var
     */
    public $token;

    /**
     * 用户对象
     * @var
     */
    public $TokenObj;

    public function init()
    {
        parent::init();
        //允许跨域
        Yii::$app->response->headers->set('Access-Control-Allow-Origin', '*');
        //返回json格式
        Yii::$app->response->format = Response::FORMAT_JSON;
    }

    /**
     * 前置方法，获取用户对象信息
     * @param \yii\base\Action $action
     * @return bool
     */
    public function beforeAction($action)
    {
        $this->token = Yii::$app->request->get('token', '');
        if (!empty($this->token)) {
            $this->TokenObj = Yii::$app->cache->get($this->token);
        }
        return parent::beforeAction($action); // TODO: Change the autogenerated stub
    }

    /**
     * 后置方法，保存用户对象信息
     * @param \yii\base\Action $action
     * @param mixed $result
     * @return mixed
     */
    public function afterAction($action, $result)
    {
        if (!empty($this->TokenObj)) {
            //保存信息
            Yii::$app->cache->set($this->TokenObj->token, $this->TokenObj, OC['session_lifetime']);
        }
        return parent::afterAction($action, $result); // TODO: Change the autogenerated stub
    }

    /**
     * 仅限制自己的域名可访问
     */
    public function onlySelfDomain()
    {
        if (isset($_SERVER['HTTP_ORIGIN'])) {
            //获取双斜杠的位置
            $domainArr = preg_split('/:\/\//', $_SERVER['HTTP_ORIGIN']);
            //获取请求的域名
            $originDomain = $domainArr[1];
            //分割字符串
            $originArr = explode('.', $originDomain);
            // 设置支持跨域
            //如果子域名在定义的列表内
            if (in_array($originArr[0], SUB_DOMAIN_LIST)) {
                //允许跨域
                Yii::$app->response->headers->set('Access-Control-Allow-Origin', HTTP . '://' . $originArr[0] . '.' . DOMAIN);
            }
        }
    }
}